package com.central.dataManage.controller;


import com.central.common.annotation.LoginUser;
import com.central.common.annotation.RequiredPermission;
import com.central.common.constant.PermissionConstants;
import com.central.common.enums.PrivilegeType;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.utils.UserRoleUtil;
import com.central.dataManage.model.ProjectPrivileges;
import com.central.common.model.TableInfo;
import com.central.dataManage.model.UserPrivileges;
import com.central.dataManage.service.IDatasourceService;
import com.central.dataManage.service.ITableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;

/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@Slf4j
@RestController
@Api(tags = "表权限模块api")
@RequestMapping(value = "/privilegeManage")
public class PrivilegeManageController {

    @Autowired
    private ITableService tableService;
    @Autowired
    private IDatasourceService datasourceService;


    @ApiOperation(value = "数据权限申请")
    @PostMapping("/apply")
    public Result apply(Long tableId, String reason,@RequestBody Set<PrivilegeType> privileges) {
        //TODO 数据权限申请
        return Result.failed("未开发");
    }

    @ApiOperation(value = "数据权限项目列表")
    @PostMapping("/findProjectPrivileges")
    public Result<List<ProjectPrivileges>> findProjectPrivileges(Long tableId) {
        return tableService.findProjectPrivileges(tableId);
    }

    @ApiOperation(value = "添加项目数据权限")
    @PostMapping("/addProjectPrivileges")
    public Result addProjectPrivileges(@ApiIgnore @LoginUser SysUser user, Long tableId, Long proId, @RequestBody List<PrivilegeType> privileges) throws SQLException {
        //判断是否是全局数据管理员或数据负责人
        if (UserRoleUtil.checkGloDataAdmin(user.getRoles())){
            return tableService.addProjectPrivileges(tableId,proId,privileges);
        }else {
            TableInfo tableInfo = tableService.getById(tableId);
            if(tableInfo!=null){
                SysUser tableOwner = tableService.findTableOwner(tableInfo.getDatasourceId(), tableInfo.getDbName(), tableInfo.getTableName());
                if(tableOwner!=null && user.getId()==tableOwner.getId()){
                    return tableService.addProjectPrivileges(tableId,proId,privileges);
                }else {
                    return Result.failed("操作失败：权限不足");
                }
            }else {
                return Result.failed("操作失败：表不存在");
            }
        }
    }



    @ApiOperation(value = "获取表责任人")
    @GetMapping("/findTableOwner")
    public SysUser findTableOwner(Long datasourceId,String dbName,String tableName) {
        return tableService.findTableOwner(datasourceId,dbName,tableName);
    }

    @ApiOperation(value = "修改表责任人")
    @GetMapping("/updateTableOwner")
    @RequiredPermission(PermissionConstants.GLO_DATA_ADMIN)
    public Result updateTableOwner(Long datasourceId, String dbName, String tableName, Long userId) {
        try {
            tableService.updateTableOwner(datasourceId,dbName,tableName,userId);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("tableManage-updateTableOwner-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "获取当前项目成员表权限")
    @GetMapping("/findUserPrivileges")
    public Result<List<UserPrivileges>> findUserPrivileges(@ApiIgnore @LoginUser SysUser user, Long tableId) {
        return tableService.findUserPrivileges(user.getCurrentProjectId(),tableId);
    }

    @ApiOperation(value = "添加用户数据权限")
    @PostMapping("/addUserPrivileges")
    @RequiredPermission(PermissionConstants.PRO_DATA_ADMIN)
    public Result addUserPrivileges(@ApiIgnore @LoginUser SysUser user,Long userId, Long tableId,@RequestBody List<PrivilegeType> privileges) throws SQLException, ExecutionException, InterruptedException {
        return tableService.addUserPrivileges(user,userId,tableId,privileges);
    }

    /**
     * 获取用户所有的表权限字典
     * @param datasourceId
     * @param proId
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取用户所有的表权限字典")
    @PostMapping("/pv/getAllTablePrivilege")
    Map<String, List<PrivilegeType>> getAllTablePrivilege(@RequestParam("datasourceId") Long datasourceId, @RequestParam("proId") Long proId, @RequestParam("userId") Long userId,@RequestBody Set<String> tables){
        return tableService.getAllTablePrivilege(datasourceId,proId,userId,tables);
    }


    /**
     * 系统hive库中创建用户角色，并将用户数据库授权给用户角色
     * @param proName
     * @param username
     * @return
     */
    @ApiOperation(value = "系统hive库中创建用户角色，并将用户数据库授权给用户角色")
    @GetMapping("/pv/createUserRoleOfHive")
    public Result createUserRoleOfHive(String proName,String username) throws SQLException {
        return datasourceService.createUserRoleOfHive(proName,username);
    }

    /**
     * 创建用户在hdfs的家目录
     * @param proName
     * @param username
     * @return
     */
    @ApiOperation(value = "创建用户在hdfs的家目录")
    @GetMapping("/pv/createUserHdfsHomeDir")
    public Result createUserHdfsHomeDir(String proName,String username) throws IOException {
        return datasourceService.createUserHdfsHomeDir(proName,username);
    }
}
